<?php
/**
  * //w/w/w.s/h/u/o/t//u/p/u c/o/m  说 图/谱/源/码/分/享
 */
defined('IN_IA') or exit('Access Denied');
/**
 * 给用户发送支付成功推送信息
 * @param $orderData    //订单信息
 * @param $prepay_id    //支付成功formid
 * @param $touser       //用户openid
 * @param $uniacid      //小程序唯一标志
 * @param $page         //链接地址
 */
function send_msg_to_user($orderData,$prepay_id,$touser,$uniacid,$page){
    $wxData=pdo_get('cqkundian_farm_wx_set',array('uniacid'=>$uniacid));
    $setting = uni_setting($uniacid, array('payment'));
    $wechat = $setting['payment']['wechat'];
    $sql = 'SELECT `key`,`secret` FROM ' . tablename('account_wxapp') . ' WHERE `acid`=:acid';
    $row = pdo_fetch($sql, array(':acid' => $wechat['account']));

    $access_token = get_accessToken($row['key'],$row['secret'],$uniacid);
    $value = array(
        "keyword1"=>array(
            "value"=>'购物消费',
            "color"=>"#4a4a4a"
        ),
        "keyword2"=>array(
            "value"=>date("Y-m-d H:i:s",$orderData['create_time']),
            "color"=>"#9b9b9b"
        ),
        "keyword3"=>array(
            "value"=>$orderData['total_price'],
            "color"=>"#9b9b9b"
        ),
    );
    $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token;
    $dd = array();
    $dd['touser']=$touser;
    $dd['template_id']=$wxData['wx_small_template_id'];
    $dd['page']=$page;
    $dd['form_id']=$prepay_id;
    $dd['data']=$value;
    $dd['color']='';
    $dd['emphasis_keyword']='';    //模板需要放大的关键词，不填则默认无放大
    $result = https_curl_json($url,$dd,'json');
    if($result){
        echo json_encode(array('state'=>1,'msg'=>$result));
    }else{
        echo json_encode(array('state'=>2,'msg'=>$result));
    }
}

/**
 * 向用户发送设备信息
 * @param $formId       //formid
 * @param $web_did      //设备号
 * @param $info         //提示信息
 * @param $touser       //用户openid
 * @param $page         //链接页面
 * @param $uniacid      //小程序唯一标识
 */
function sendDeviceInfoToUser($formId,$web_did,$info,$touser,$page,$uniacid){
    $wxData=pdo_get('cqkundian_farm_wx_set',array('uniacid'=>$uniacid));
    $setting = uni_setting($uniacid, array('payment'));
    $wechat = $setting['payment']['wechat'];
    $sql = 'SELECT `key`,`secret` FROM ' . tablename('account_wxapp') . ' WHERE `acid`=:acid';
    $row = pdo_fetch($sql, array(':acid' => $wechat['account']));

    $access_token = get_accessToken($row['key'],$row['secret'],$uniacid);
    $value = array(
        "keyword1"=>array(
            "value"=>$web_did,
            "color"=>"#4a4a4a"
        ),
        "keyword2"=>array(
            "value"=>$info,
            "color"=>"#9b9b9b"
        ),
        "keyword3"=>array(
            "value"=>date("Y-m-d H:i:s",time()),
            "color"=>"#9b9b9b"
        ),
    );
    $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token;
    $dd = array();
    $dd['touser']=$touser;
    $dd['template_id']=$wxData['mini_device_template_id'];
    $dd['page']=$page;
    $dd['form_id']=$formId;
    $dd['data']=$value;
    $dd['color']='';
    $dd['emphasis_keyword']='';    //模板需要放大的关键词，不填则默认无放大
    $result = https_curl_json($url,$dd,'json');
    return $result;
}

function sendServiceInfoToUser($uniacid,$title,$info,$touser,$page,$formId){
    $wxData=pdo_get('cqkundian_farm_wx_set',array('uniacid'=>$uniacid));
    $setting = uni_setting($uniacid, array('payment'));
    $wechat = $setting['payment']['wechat'];
    $sql = 'SELECT `key`,`secret` FROM ' . tablename('account_wxapp') . ' WHERE `acid`=:acid';
    $row = pdo_fetch($sql, array(':acid' => $wechat['account']));

    $access_token = get_accessToken($row['key'],$row['secret'],$uniacid);
    $value = array(
        "keyword1"=>array(
            "value"=>$title,
            "color"=>"#4a4a4a"
        ),
        "keyword2"=>array(
            "value"=>$info,
            "color"=>"#9b9b9b"
        ),
        "keyword3"=>array(
            "value"=>date("Y-m-d H:i:s",time()),
            "color"=>"#9b9b9b"
        ),
    );
    $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token;
    $dd = array();
    $dd['touser']=$touser;
    $dd['template_id']=$wxData['mini_services_template_id'];
    $dd['page']=$page;
    $dd['form_id']=$formId;
    $dd['data']=$value;
    $dd['color']='';
    $dd['emphasis_keyword']='';    //模板需要放大的关键词，不填则默认无放大
    $result = https_curl_json($url,$dd,'json');
    return $result;
}


/**
 * 给管理员发送订单通知
 * @param $touser           //管理员openid
 * @param $orderData        //订单信息
 * @param $uniacid          //小程序唯一标志
 * @return bool             //返回值
 */
function send_template_message($touser,$orderData,$uniacid){
    $wxData=pdo_get('cqkundian_farm_wx_set',array('uniacid'=>$uniacid));
    $access_token = get_Wx_accessToken($wxData['wx_appid'],$wxData['wx_secret'],$uniacid);
    $data=array(
        'first'=>array('value'=>'您有新的订单'),
        'keyword1'=>array("value"=>$orderData['order_number']),
        'keyword2'=>array("value"=>$orderData['total_price']),
        'keyword3'=>array("value"=>'请尽快送达'),
        'keyword4'=>array("value"=>$orderData['phone']),
        'keyword5'=>array("value"=>$orderData['address']),
    );
    $template = array(
        'touser' => $touser,
        'template_id' => $wxData['wx_template_order_id'],
        'data' => $data,
        "miniprogram"=>array(
            "appid"=>'',
            "pagepath"=>"kundian_farm/pages/center/shop_order/index"
        )
    );
    $json_template = json_encode($template);
    $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
    $dataRes = http_request($url, urldecode($json_template));
    if ($dataRes->errcode == 0) {
        return true;
    } else {
        return false;
    }
}

/**
 * 种子、土地购买，家畜领养订单通知
 * @param $touser
 * @param $orderData
 * @param $uniacid
 * @return bool
 */
function send_other_template_message($touser,$orderData,$uniacid){
    $wxData=pdo_get('cqkundian_farm_wx_set',array('uniacid'=>$uniacid));
    $access_token = get_Wx_accessToken($wxData['wx_appid'],$wxData['wx_secret'],$uniacid);
    $data=array(
        'first'=>array('value'=>'您有新的订单'),
        'keyword1'=>array("value"=>$orderData['order_number']),
        'keyword2'=>array("value"=>$orderData['body']),
        'keyword3'=>array("value"=>$orderData['total_price']),
        'keyword4'=>array("value"=>'已支付'),
        'keyword5'=>array("value"=>date("Y-m-d H:i:s",$orderData['create_time'])),
    );
    $template = array(
        'touser' => $touser,
        'template_id' => $wxData['wx_shop_template_id'],
        'data' => $data,
        "miniprogram"=>array(
            "appid"=>'',
            "pagepath"=>""
        )
    );
    $json_template = json_encode($template);
    $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
    $dataRes = http_request($url, urldecode($json_template));
    if ($dataRes->errcode == 0) {
        return true;
    } else {
        return false;
    }
}

/**
 * 订单取消通知
 * @param $touser       //通知用户
 * @param $orderData    //订单编号
 * @param $uniacid      //小程序唯一标识
 * @return bool         //返回值
 */
function cancelOrderSendTemplate($touser,$orderData,$uniacid){
    $wxData=pdo_get('cqkundian_farm_wx_set',array('uniacid'=>$uniacid));
    $access_token = get_Wx_accessToken($wxData['wx_appid'],$wxData['wx_secret'],$uniacid);
    $data=array(
        'first'=>array('value'=>'订单取消通知'),
        'keyword1'=>array("value"=>$orderData['order_number']),
        'keyword2'=>array("value"=>$orderData['total_price']),
        'keyword3'=>array("value"=>date("Y-m-d H:i:s",time())),
    );
    $template = array(
        'touser' => $touser,
        'template_id' => $wxData['wx_cancel_template_id'],
        'data' => $data,
        "miniprogram"=>array(
            "appid"=>'',
            "pagepath"=>""
        )
    );
    $json_template = json_encode($template);
    $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
    $dataRes = http_request($url, urldecode($json_template));
    if ($dataRes->errcode == 0) {
        return true;
    } else {
        return false;
    }
}


/**
 * 获取微信公众号access_token
 * @param $appid        //微信公众号appid
 * @param $secret       //微信公众号密钥
 * @param $uniacid      //小程序唯一标志
 * @return array|bool|Memcache|mixed|Redis|string
 */
function get_Wx_accessToken($appid,$secret,$uniacid){
    if(cache_load('kundian_farm_access_token_wx_time'.$uniacid)>time()){
        return cache_load('kundian_farm_access_token_wx'.$uniacid);
    }else{
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
        $result = http_request($url);
        $res = json_decode($result,true);
        if($res){
            cache_write('kundian_farm_access_token_wx_time'.$uniacid,time()+7000);
            cache_write('kundian_farm_access_token_wx'.$uniacid,$res['access_token']);
            return $res['access_token'];
        }else{
            return 'api return error';
        }
    }
}

/**
 * 获取小程序access_token
 * @param $appid        //小程序appid
 * @param $secret       //小程序密钥
 * @param $uniacid      //小程序唯一标识
 * @return array|bool|Memcache|mixed|Redis|string
 */
function get_accessToken($appid,$secret,$uniacid){
    if(cache_load('kundian_farm_access_token_time'.$uniacid) > time()){
        return cache_load('kundian_farm_access_token'.$uniacid);
    }else{
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
        $result = http_request($url);
        $res = json_decode($result,true);
        if($res){
            cache_write('kundian_farm_access_token_time'.$uniacid,time()+7000);
            cache_write('kundian_farm_access_token'.$uniacid,$res['access_token']);
            return $res['access_token'];
        }else{
            return 'api return error';
        }
    }
}

/* 发送json格式的数据，到api接口 -xzz0704  */
function https_curl_json($url,$data,$type){
    if($type=='json'){//json $_POST=json_decode(file_get_contents('php://input'), TRUE);
        $headers = array("Content-type: application/json;charset=UTF-8","Accept: application/json","Cache-Control: no-cache", "Pragma: no-cache");
        $data=json_encode($data);
    }
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers );
    $output = curl_exec($curl);
    if (curl_errno($curl)) {
        echo 'Errno'.curl_error($curl);//捕抓异常
    }
    curl_close($curl);
    return $output;
}
function http_request($url,$data=array()){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    // POST数据
    curl_setopt($ch, CURLOPT_POST, 1);
    // 把post的变量加上
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

/**
 * 获取小程序的配置信息
 * @param $field
 * @param $condition
 * @return array
 */
function getFarmSetData($field,$condition){
    $condition['ikey']=$field;
    $setData=pdo_getall('cqkundian_farm_set',$condition);
    $list=array();
    foreach ($setData as $key=>$value){
        $list[$value['ikey']]=$value['value'];
    }
    return $list;
}
/**
 * 佣金记录
 * @param $uid
 * @param $one_sale_uid
 * @param $price
 * @param $remark
 * @param $do_type
 * @param $uniacid
 */
function recordSalePrice($uid,$one_sale_uid,$price,$remark,$do_type,$uniacid,$order_type,$order_id){
    $data=array(
        'uid'=>$uid,
        'one_sale_uid'=>$one_sale_uid,
        'price'=>$price,
        'remark'=>$remark,
        'do_type'=>$do_type,
        'uniacid'=>$uniacid,
        'create_time'=>time(),
        'order_type'=>$order_type,
        'order_id'=>$order_id
    );

    pdo_insert('cqkundian_farm_sale_price_record',$data);

}

/**
 * 分销佣金发放
 * @param $orderData
 * @param $uniacid
 * @param $order_type
 */
function saleSendPirce($orderData,$uniacid,$order_type){
    $res=0;
    $user=pdo_get('cqkundian_farm_user',array('uniacid'=>$uniacid,'uid'=>$orderData['uid']));
    if($user['one_distributor']!=0) {
        $one_sale = pdo_get('cqkundian_farm_user', array('uniacid' => $uniacid, 'uid' => $user['one_distributor']));
        //一级分销商加佣金
        $update_one_sale=array(
            'total_price +='=>$orderData['one_price'],
            'price +='=>$orderData['one_price'],
        );
        $res+=pdo_update('cqkundian_farm_user',$update_one_sale,array('uniacid'=>$uniacid,'uid'=>$user['one_distributor']));
        recordSalePrice($user['one_distributor'],$orderData['uid'],$orderData['one_price'],'一级分销佣金',1,$uniacid,$order_type,$orderData['id']);
        if($one_sale['one_distributor']!=0){
            $update_two_sale=array(
                'total_price +='=>$orderData['two_price'],
                'price +='=>$orderData['two_price'],
            );
            //二级分销商加佣金
            $res+=pdo_update('cqkundian_farm_user',$update_two_sale,array('uniacid'=>$uniacid,'uid'=>$one_sale['one_distributor']));
            recordSalePrice($one_sale['one_distributor'],$orderData['uid'],$orderData['two_price'],'二级分销佣金',1,$uniacid,$order_type,$orderData['id']);
        }
    }else{
        $res=0;
    }
    return $res;
}
